<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
define('NOSESSION',true);
define('TC_API',true);
require_once '../core/core.php';
if($_AR['close']){
	exi('站点已关闭','error');
}
set_exi(function($message,$type,$action,$url){
	ob_clean();
	if($type=='error'){		
		exit('');
	}else{
		$message=ijson_encode($message);
		addwork_logs($message);
		exit($message);
	}
	
});
if(!$_RQ['msg_signature'] || !$_RQ['timestamp'] || !$_RQ['nonce']){
	addwork_logs('非法访问，只接受企业微信发起！');
	exit('非法访问，只接受企业微信发起！');
}
//校验签名
//签名验证，交给不同的接口
/*if($_RQ['echostr']){
	$signkey = array($setting['token'], $_RQ['timestamp'], $_RQ['nonce'], $_RQ['echostr']);
}else{
	$signkey = array($setting['token'], $_RQ['timestamp'], $_RQ['nonce']);
}
sort($signkey, SORT_STRING);
$signString = implode('',$signkey);
$signString = sha1($signString);
if($signString !=$_RQ['msg_signature']){
	exit('error4');
}*/
if($_RQ['i']){
	$_SESSION['uniacid']=intval($_RQ['i']);
}
//来自自建应用
if($_RQ['app_id']){
	$wxwork_app=pdo_get('core_account_wxwork_app',array('id'=>intval($_RQ['app_id'])),array('id','pid','title','appid','appsecret','wxwork_id'));
	$wxwork=pdo_get('core_account_wxwork',array('id'=>$wxwork_app['wxwork_id']),array('id','appid','token','aeskey'));
	$setting['token']=$wxwork['token'];
	$setting['aeskey']=$wxwork['aeskey'];
	$corpid=$wxwork['appid'];
}elseif($_RQ['wxwork_id']){
	$wxwork=pdo_get('core_account_wxwork',array('id'=>$_RQ['wxwork_id']),array('id','appid','token','aeskey'));
	$setting['token']=$wxwork['token'];
	$setting['aeskey']=$wxwork['aeskey'];
	$corpid=$wxwork['appid'];
}else{
	//SAAS服务商配置
	$setting=core_setting('work_weixin');
	$setting['token']=$setting['token']?:'oNyvVWjt2pGrihehJ6p4uxeJwsre';
	if(!$setting['token']){
		addwork_logs('校验签名失败，未设置token！');
		exit('校验签名失败，未设置token！');
	}
	$corpid=$setting['corpid'];
}
if($_RQ['pid']){
	$open_plugin=pdo_get('core_open_plugin',array('id'=>intval($_RQ['pid'])),array('pid','uniacid','isplugin','saastype','suite_id','corpid','token','aeskey'));
	$corpid=$open_plugin['suite_id'];
	$corpid=$corpid && $_RQ['isopen']?$corpid:$setting['corpid'];
	if($open_plugin['uniacid']){
		$_SESSION['uniacid']=$_SESSION['uniacid']?:$open_plugin['uniacid'];
		if($_RQ['echostr'] && $open_plugin['corpid']){
			$corpid=$open_plugin['corpid'];
		}
		$setting['token']=$open_plugin['token'];
		$setting['aeskey']=$open_plugin['aeskey'];
	}
	$_SESSION['workeropen_pid']=intval($_RQ['pid']);
}
//先将消息体解密
require ROOT_D.'/core/library/wxwork/callback/WXBizMsgCrypt.php';
$wxcpt=new WXBizMsgCrypt($setting['token'], $setting['aeskey'], $corpid);
$post=file_get_contents('php://input');
$message='';
//验证URL有效性
if($_RQ['echostr']){
	$errCode = $wxcpt->VerifyURL($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $_RQ['echostr'], $message);
	if ($errCode == 0) {
		exit($message);
	}else{
		addwork_logs('消息体解密失败：'.$errCode);
		exit('消息体解密失败：'.$errCode);
	}
}else{
	$errCode = $wxcpt->DecryptMsg($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $post, $message);
}
if($errCode){
	addwork_logs('消息体解密失败：'.$errCode);
	exit('消息体解密失败：'.$errCode);
}
$postdata=xml2array($message);
//addwork_logs(ijson_encode($postdata));
if($postdata['InfoType']=='create_auth' || $postdata['InfoType']=='reset_permanent_code'){
	//安装创建通知/授权成功通知
	$suite_id=$postdata['SuiteId'];
	$AuthCode=$postdata['AuthCode'];
	if(!$_SESSION['workeropen_pid']){
		$plugin=pdo_get('core_open_plugin',array('suite_id'=>$suite_id));
		if(!$plugin){
			addwork_logs('找不到绑定的应用');
			exit('找不到绑定的应用！');
		}
		$_SESSION['workeropen_pid']=$plugin['id'];
	}
	if(!$AuthCode){
		addwork_logs('缺少用户AuthCode，实例授权失败！');
		exit('缺少用户AuthCode，实例授权失败！');
	}
	//获取企业永久授权码/企业信息
	$content=model('core/wxwork_api',$_SESSION['workeropen_pid'])->get_permanent_code($AuthCode);
	//检查用户是否存在(通过企业微信ID作为唯一性)；
	if($open_plugin['uniacid']){
		if($open_plugin['saastype']){
	        $jy_merch=cfc('core')->plugin_exists('jy_merch');
    		if($jy_merch){
    			model('jy_merch/wxwork')->upitem($merchid,$content,'',$open_plugin['pid']);
    		}
	    }else{
    		//多商户安装三方应用
    		$state=str_array($postdata['State'],'merchid_');
    		$merchid=$state[1];
    		if($merchid){
    			$jy_merch=cfc('core')->plugin_exists('jy_merch');
    			if($jy_merch){
    				model('jy_merch/wxwork')->upitem($merchid,$content,'',$open_plugin['pid']);
    			}
    		}
	    }
	}elseif($postdata['InfoType']=='create_auth'){
		$_SESSION['uniacid']=pdo_getcolumn('core_open_user',array('open_uid'=>$content['auth_corp_info']['corpid']),'uniacid');
		if($_SESSION['uniacid']){
			model('core/open_app')->update($_SESSION['workeropen_pid']);
		}else{
			//创建用户
			do{
				$username='wxwork_'.random(5,true);
				$username=$content['auth_user_info']['userid']?:$username;
				$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
			}while($check);
			$work_weixin=core_setting('work_weixin');
			$new_member=array(
				'name'=>$username,
				'password'=>random(8),
				'groupid'=>$work_weixin['groupid'],
				'nickname'=>$content['auth_corp_info']['corp_name'],
			);
			if($postdata['mobile']){
				$new_member['mobile']=$postdata['mobile'];
			}
			$_SESSION['uniacid']=cfc('user')->create_user($new_member);
			$user=array(
				'uniacid'=>$_SESSION['uniacid'],
				'open_id'=>'1006',//1006表示来自企业微信的用户
				'open_uid'=>$content['auth_corp_info']['corpid'],
			);
			pdo_insert('core_open_user',$user);
		}
	}
	exit('success');
}elseif($_GET['auth_code'] && $_GET['state']){
	//从服务商网站发起，获取当前会话
	session_id($_GET['state']);
	model('core/wxwork_api',$_SESSION['workeropen_pid'])->get_permanent_code($_GET['auth_code']);
}elseif($postdata['InfoType']=='suite_ticket'){
	//推送suite_ticket
	if($_RQ['pid']){
		pdo_update('core_open_plugin',array('suite_ticket'=>$postdata['SuiteTicket']),array('id'=>intval($_RQ['pid'])));
	}elseif($postdata['SuiteId']){
		pdo_update('core_open_plugin',array('suite_ticket'=>$postdata['SuiteTicket']),array('suite_id'=>$postdata['SuiteId']));
	}
}elseif($postdata['MsgType']=='event'){
	//事件消息
	if($postdata['AuthCorpId']){
		//三方商户安装应用
		$wxwork_id=pdo_getcolumn('core_account_wxwork',array('merchid >'=>0,'appid'=>$postdata['AuthCorpId'],'uniacid'=>$_SESSION['uniacid']),'id');
		$_SESSION['onemerchid']=pdo_getcolumn('core_account_wxwork_app',array('pid'=>$open_plugin['pid'],'merchid >'=>0,'wxwork_id'=>$wxwork_id,'uniacid'=>$_SESSION['uniacid']),'merchid');
	}
	if($postdata['Event']=='change_external_contact'){
		if($postdata['ChangeType']=='add_external_contact'){
			//成员添加外部联系人时，回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->add_external_contact($postdata,true);
			//加客户（客户扫码加企业员工）
			if($postdata['WelcomeCode']){
				model('core/wxwork_userapi',$_RQ['app_id'])->send_welcome_msg($postdata,true);
			}
		}elseif($postdata['ChangeType']=='edit_external_contact'){
			//成员修改外部联系人的备注、手机号或标签时，回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->edit_external_contact($postdata,true);
		}elseif($postdata['ChangeType']=='add_half_external_contact'){
			//外部联系人添加了配置了客户联系功能且开启了免验证的成员时（此时成员尚未确认添加对方为好友），回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->add_half_external_contact($postdata,true);
		}elseif($postdata['ChangeType']=='del_external_contact'){
			//成员删除外部联系人时，回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->del_external_contact($postdata,true);
		}elseif($postdata['ChangeType']=='del_follow_user'){
			//成员被外部联系人删除时，回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->del_follow_user($postdata,true);
		}elseif($postdata['ChangeType']=='transfer_fail'){
			//企业将客户分配给新的成员接替后，客户添加失败时回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->transfer_fail($postdata,true);
		}
	}elseif($postdata['Event']=='change_external_chat'){
		if($postdata['ChangeType']=='create'){
			//有新增客户群时，回调该事件。收到该事件后，企业可以调用获取客户群详情接口获取客户群详情。
			model('core/wxwork_userapi',$_RQ['app_id'])->chat_add($postdata,true);
		}elseif($postdata['ChangeType']=='update'){
			//客户群被修改后（群名变更，群成员增加或移除，群主变更，群公告变更），回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->chat_update($postdata,true);
		}elseif($postdata['ChangeType']=='dismiss'){
			//当客户群被群主解散后，回调该事件
			model('core/wxwork_userapi',$_RQ['app_id'])->chat_dismiss($postdata,true);
		}
	}elseif($postdata['Event']=='change_external_tag'){
		if($postdata['ChangeType']=='create'){
			//企业/管理员创建客户标签/标签组时（包括规则组的标签），回调此事件
			model('core/wxwork_userapi',$_RQ['app_id'])->tag_add($postdata,true);
		}elseif($postdata['ChangeType']=='update'){
			//当企业客户标签/标签组（包括规则组的标签）被修改时，回调此事件。收到该事件后
			model('core/wxwork_userapi',$_RQ['app_id'])->tag_update($postdata,true);
		}elseif($postdata['ChangeType']=='delete'){
			//当企业客户标签/标签组被删除改时，回调此事件
			model('core/wxwork_userapi',$_RQ['app_id'])->tag_delete($postdata,true);
		}
	}
}
exit('success');
function addwork_logs($message){
	//录入消息日志
	if($_AR['system']['wxlog']){
		$data=$message;
		$data=$data."\n*******************************\n";
		$i=$_SESSION['uniacid']?:1;
		file_put_contents(ROOT_AT.'error_logs/wxwork'.$i.'.log',$data,FILE_APPEND);
	}
}